package com.hzit.ms.service.impl;

import com.hzit.ms.controller.UserController;
import com.hzit.ms.mapper.UserInfoMapper;
import com.hzit.ms.model.UserInfo;
import com.hzit.ms.resp.RespVo;
import com.hzit.ms.resp.UserData;
import com.hzit.ms.service.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.ObjectUtils;

import java.util.Objects;

/**
 * 用户相关接口实现类
 */
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    private Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private ValueOperations<String, Object> valueOperations;



    @Override
    public RespVo<UserData> userLogin(String mobile, String password) {

        RespVo respVo = new RespVo();

        //shiro 登录
        UserInfo userInfo = userInfoMapper.queryUserInfoByMobile(mobile);

        if (Objects.isNull(userInfo)){
            logger.info("手机号:{}在系统中不存在",mobile);
            respVo.setCode(-1);
            respVo.setMsg("手机号在系统中不存在");
            return respVo;
        }

        //判断密码是否相等
        if (!password.equals(userInfo.getPassword())){
            logger.info("手机号:{}对应的密码:{}不正确",mobile,password);
            respVo.setCode(-1);
            respVo.setMsg("密码不正确");
            return respVo;
        }

        //登录成功,用户信息写入redis

        respVo.setCode(0);
        respVo.setMsg("登录成功");

        UserData userData  = new UserData();
        userData.setUserId(String.valueOf(userInfo.getId()));
        userData.setUserName(userInfo.getUserName());
        respVo.setData(userData);

        //用户信息写入redis.

        //唯一
        String userKey = "userInfo:" + userInfo.getId() ;
        valueOperations.set(userKey,userInfo);

        return respVo;
    }
}
